<?php


namespace app\manage\middleware;


use app\common\traits\AuthTrait;
use app\manage\loader\ManageServices;
use think\Exception;
use think\facade\Config;
use yiqiniu\extend\library\GlobalParam;

/**
 * 认证类
 */
class Auth
{

    use AuthTrait;

    /**
     * @param          $request
     * @param \Closure $next
     * @return mixed|void
     * @throws \Exception
     */
    public function handle($request, \Closure $next)
    {
        $no_auth = Config::get('config.no_auth');


        $header = $request->header();
        // 提取header的APP
        $request->request_app = $this->parseHeaderApp($header);
        // 保存到全局变量中
        GlobalParam::getInstance()->put('app', $request->request_app);

        if ($this->checkNoAuth($request, $no_auth)) {
            return $next($request);
        }

        try {

            $authorization = $this->parseHeaderAuthorization($header);
            if (empty($authorization)) {
                api_result(API_TIMEOUT, '登录超时,请重新登录');
            }

            // 验证登录信息
            $msg = '';
            $authInfo = ManageServices::Manager()->verityLogin($authorization, $request->request_app, $msg);
            if ($authInfo === false) {
                api_result(API_ERROR, $msg);
            }
            GlobalParam::getInstance()->put('userinfo', $authInfo);

            $request->request_authInfo = $authInfo;
            return $next($request);
        } catch (Exception $e) {
            api_result($e);
        }

    }


    public function parseHeaderAuthorization(array $header)
    {
        $authStr = $header[$this->_authField] ?? '';
        if (empty($authStr)) {
            $authStr = $header[ucfirst($this->_authField)] ?? '';
        }
        return strpos($authStr, ' ') !== false ? explode(' ', $authStr)[1] : $authStr;
    }


}
